package com.more.spring.boot.config;

import com.more.spring.boot.mapper.UserMapper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SqlSessionFactoryConfig {
    private static final SqlSessionFactory sqlSessionFactory;

    private static final Properties properties;

    static {
        //加载properties
        properties = loadProPerties();

        //配置数据源
        DataSource dataSource = SqlSessionFactoryConfig.getDataSource(properties);

        //配置事务工厂
        JdbcTransactionFactory jdbcTransactionFactory = new JdbcTransactionFactory();

        //创建环境
        Environment development = new Environment("development", jdbcTransactionFactory, dataSource);

        //创建mybatis配置
        Configuration configuration = new Configuration(development);
//        configuration.addMapper(UserMapper.class);

        //构建SqlSessionFactory

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public static <T> void registerMapper(Class<T> mapperClass){
        Configuration configuration = sqlSessionFactory.getConfiguration();
        if(!configuration.hasMapper(mapperClass)){
            configuration.addMapper(mapperClass);
        }
    }

    /**
     * 加载properties配置文件
     */
    private static Properties loadProPerties() {
        Properties properties = new Properties();
        try (InputStream inputStream = SqlSessionFactoryConfig.class.getClassLoader().getResourceAsStream("mybatis.properties")) {

            if (inputStream == null) {
                throw new RuntimeException("未读取mybatis.properties文件");
            }

            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return properties;
    }

    /**
     * 配置HikariDataSource
     *
     * @return
     */
    private static DataSource getDataSource(Properties properties) {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setUsername(properties.getProperty("mysql.username"));
        hikariConfig.setPassword(properties.getProperty("mysql.password"));
        hikariConfig.setJdbcUrl(properties.getProperty("mysql.url"));
        hikariConfig.setDriverClassName(properties.getProperty("mysql.driver"));
        return new HikariDataSource(hikariConfig);
    }
}
